package com.mzy.linear_struct.subject;

/**
 * @Author: codermzy
 * @Date: 2024/04/15/8:59
 * @Description:
 */
public class 搜索插入位置35 {

    public int searchInsert(int[] nums, int target) {
        if(nums == null) {
            return -1;
        }
        if(nums[0] > target) {
            return 0;
        }
        if(nums[nums.length - 1] < target) {
            return nums.length;
        }

        int left = 0;
        int right = nums.length - 1;
        int mid = 0;
        while (left <= right) {
            mid = (left + right) / 2;
            if (nums[mid] > target) {
                mid = right;
                right = mid - 1;
            } else if (nums[mid] < target) {
                mid = left;
                left = mid + 1;
            } else {
                return mid;
            }
        }

        return mid;
    }


    public int searchInsert1(int[] nums, int target) {
        if(nums == null) {
            return -1;
        }
        if(nums[0] > target) {
            return 0;
        }
        if(nums[nums.length - 1] < target) {
            return nums.length;
        }

        int left = 0;
        int right = nums.length - 1;
        int mid = 0;
        while (left <= right) {
            mid = (left + right) / 2;
            if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                return mid;
            }
        }

        return left;
    }

    public static void main(String[] args) {
        int[] nums = {1,3,5,6}; // 2
        //            0 1 2 3

        System.out.println(new 搜索插入位置35().searchInsert(nums, 2)); // 1
    }
}
